package com.mdjnu.controller;

import com.mdjnu.pojo.Result;
import com.mdjnu.pojo.User;
import com.mdjnu.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 验证码登录
     * @param email 邮箱
     * @param code 验证码
     * @return 统一响应结果
     */
    @GetMapping("/loginByEmail")
    public Result loginByEmail(@Param("email") String email,@Param("code") String code){
        User user = userService.loginByEmail(email,code);
        if(user != null){
            return Result.success(user);
        }else{
            return Result.error("验证码错误或过期");
        }
    }
    /**
     * 发送验证码
     * @param email 邮箱
     * @return 统一响应结果
     */
    @GetMapping("/sendCode")
    public Result sendCode(@Param("email") String email){
        if(email == null || email.equals("")){
            return Result.error("邮箱不能为空");
        }
        userService.sendCode(email);
        return Result.success();
    }
    @GetMapping("/loginByPassword")
    public Result loginByPassword(@Param("email") String email,@Param("password") String password){
        User user = userService.findByEmailAndPassword(email,password);
        if(user != null){
            return Result.success(user);
        }
        else {
            return Result.error("密码错误");
        }
    }

    @GetMapping("/loginByToken")
    public Result loginByToken(HttpServletRequest request){
        String token = request.getHeader("LY-Authorization");
        if(token == null || token.equals("")){
            return Result.error("身份验证过期");
        }
        return userService.loginByToken(token);
    }

    @PostMapping("/getUserByIds")
    public Result getUserByIds(@RequestBody List<Integer> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return Result.error("用户id不能为空");
        }
        return userService.getUserByIds(userIds.stream().mapToInt(Integer::intValue).toArray());
    }

}
